package net.mingsoft.basic.sao;

import com.alibaba.fastjson.JSONObject;
import net.mingsoft.basic.sao.util.SM4Util;
import net.mingsoft.config.RestTemplateConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.Objects;

@Component
public class SM4CloudService {

    private static final RestTemplate REST = new RestTemplate();

    private static final RestTemplate UN_SSL_REST = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());

    private static final HttpHeaders HEADER_APPLICATION_JSON = new HttpHeaders();

    static {
        HEADER_APPLICATION_JSON.setContentType(MediaType.APPLICATION_JSON);
    }

    @Value("${sm4.type:1}")
    private int encryptType;

    @Value("${sm4.url:http://10.1.3.49:7080/api/incident-server/incident/common/encrypt}")
    private String flkUrl;


    @Value("${sm4.url-d:http://10.1.3.49:7080/api/incident-server/incident/common/decrypt}")
    private String flkUrlDe;

    public String decrypt(String text) {
        if (encryptType == 1) {
            return text;
        }
        return cloudDecrypt(text);
    }

    public String encrypt(String text) {
        if (encryptType == 1) {
            return text;
        }
        return cloudEncrypt(text);
    }

    public String cloudDecrypt(String text) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("content", text);
        HttpEntity<String> stringHttpEntity = new HttpEntity<>(requestBody.toJSONString(), HEADER_APPLICATION_JSON);
        JSONObject responseBody = REST.postForObject(flkUrlDe, stringHttpEntity, JSONObject.class);
        if ((Integer) Objects.requireNonNull(responseBody).get("code") != 200) {
            throw new RuntimeException("请求flk解密失败");
        }
        return (String) responseBody.get("result");
    }

    public String cloudEncrypt(String text) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("content", text);
        HttpEntity<String> stringHttpEntity = new HttpEntity<>(requestBody.toJSONString(), HEADER_APPLICATION_JSON);
        JSONObject responseBody = REST.postForObject(flkUrl, stringHttpEntity, JSONObject.class);
        if ((Integer) Objects.requireNonNull(responseBody).get("code") != 200) {
            throw new RuntimeException("请求flk加密失败");
        }
        return (String) responseBody.get("result");
    }
}
